package com.kaoshi.myweb.webstruts.controller;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.kaoshi.myweb.common.seachable.Criteria;
import com.kaoshi.myweb.common.seachable.CriteriaType;
import com.kaoshi.myweb.common.seachable.QueryCondition;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author 周铁强
 * @version 1.0
 * @since 2015年6月19日 下午4:35:59
 * @desc
 */
public class BaseAction extends ActionSupport {

	protected Map<String, String> search = new HashMap<String, String>();

	/**
	 * 将 search，转换成querycondition对象
	 * @return
	 * @throws Exception
	 */
	public QueryCondition mapToCondition() throws Exception {
		QueryCondition condition = new QueryCondition();
		Criteria criteria = Criteria.newCriteria();

		for (Map.Entry<String, String> item : search.entrySet()) {
			String para = item.getKey();

			String value = item.getValue();
			if (StringUtils.isNoneBlank(value)) {
				String[] p = para.split("_");
				if (p.length == 2) {
					String column = p[0];
					String c = p[1];

					CriteriaType criteriaType = Enum.valueOf(CriteriaType.class, c);

					switch (criteriaType) {
					case eq:
						criteria.eq(column, value);
						break;
					case ge:
						criteria.ge(column, value);
						break;
					case in: {
						List<String> values = Arrays.asList(value.split(","));
						criteria.in(column, values);
					}
						break;
					case isNotNull:
						criteria.isNotNull(column);
						break;
					case gt:
						criteria.gt(column, value);
						break;
					case isNull:
						criteria.isNull(column);
						break;
					case le:
						criteria.le(column, value);
						break;
					case like:
						criteria.like(column, value);
						break;
					case lt:
						criteria.lt(column, value);
						break;
					case notEq:
						criteria.notEq(column, value);
						break;
					case notIn: {
						List<String> values = Arrays.asList(value.split(","));
						criteria.notIn(column, values);
					}
						break;
					case notLike:
						criteria.notLike(column, value);
						break;
					default:
						throw new Exception("条件不正确");
					}
				}
			}
		}
		condition.or(criteria);
		return condition;
	}

	public Map<String, String> getSearch() {
		return search;
	}

	public void setSearch(Map<String, String> search) {
		this.search = search;
	}
}
